<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\FileUpload;
use app\api\model\v1\AuditExam;
use app\api\model\v1\AuditExamFile;
use app\api\model\v1\AuthWxMenu;
use app\api\model\v1\Exam;
use app\api\model\v1\LearnTopic;
use app\api\model\v1\TopicExerciseLog;
use app\api\model\v1\Unit;
use app\api\model\v1\Users;
use app\api\model\v1\WxMenu;
use app\BaseController;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\facade\Env;
use think\Request;

class DataCenter extends BaseController
{
    use FileUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/10/22
     * @Time: 9:04
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 照片库
     */
    public function getPhotoLibraryList()
    {
        $limit = $this->request->param('limit', 10);
        $map = [];
        if ($this->request->has('unit_id') && !empty($this->request->param('unit_id'))) {
            $map[] = ['unit_id', '=', $this->request->param('unit_id')];
        } else {
            if (!empty($this->user)) {
                $childrenList = $this->search->getChildrenIds($this->user->unit_id, true);
                $map[] = array('unit_id', 'in', $childrenList);
            }
        }
        if ($this->request->has('date_of') && !empty($this->request->param('date_of'))) {
            $map[] = ['date_of', '=', $this->request->param('date_of')];
        }
        if ($this->request->has('type') && !empty($this->request->param('type'))) {
            if (intval($this->request->param('type')) === 1) {
                $map[] = array('attribute', '<>', 3); //非专项检查
            } else {
                $map[] = array('attribute', '=', 3); //专项检查
            }
        }
        $res = AuditExamFile::field('id,audit_exam_id,user_id,exam_stair_type_id,exam_second_level_id,exam_detail_id,file_path,date_of,ultimately_score,is_audit,audit_way,reason,unit_id')->with(['auditExam' => ['unit'], 'examDetail' => ['examSecondLevel' => ['examStairType']], 'user'])->where($map)->order('id desc')->paginate($limit)->each(function ($item, $key) {
            $unit_parent = $this->search->getParent($item['unit_id']);
            $img_arr = json_decode($item['file_path'], true);
            $new_img = [];
            foreach ($img_arr as $k => $v) {
                $new_img[] = $v['url'];
            }
            $item['unit_parent'] = reset($unit_parent)['unit_title'] ?? '未知';
            $item['new_img'] = $new_img;
            $item['image'] = reset($img_arr);
            return $item;
        });
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/25
     * @Time: 11:47
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 单位筛选
     */
    public function getFilterMenuList()
    {
        if (!$this->is_super) {
            $childrenList = $this->search->getChildrenIds($this->request->unit_id, true);
            $map[] = array('id', 'in', $childrenList);
        } else {
            $map = [];
        }
        $unit = Unit::field('id as value,unit_title as label,pid')->where($map)->select()->toArray();
        $tree = $this->search->menu($unit, $this->request->unit_id, 'children');
        return $this->response($tree);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/7/4 10:01
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 单位筛选 -- 去除专项
     */
    public function getFilterMenuListPT()
    {
        if (!$this->is_super) {
            $childrenList = $this->search->getChildrenIds($this->request->unit_id, true);
            $map[] = array('id', 'in', $childrenList);
        } else {
            $map = [];
        }
        $map[] = array('attribute', '<>', 3);
        $unit = Unit::field('id as value,unit_title as label,pid')->where($map)->select()->toArray();
        $tree = $this->search->menu($unit, $this->request->unit_id, 'children');
        return $this->response($tree);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/22
     * @Time: 16:48
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取单位
     */
    public function getUserDataInfo()
    {
        //获取本身和下级单位单位的id
//        $Unit = Unit::select()->toArray();
//        $search = $this->tree->instance()->init($Unit, 'pid');
        if (!$this->is_super) {
            $childrenList = $this->search->getChildrenIds($this->request->unit_id, true);
            $map[] = array('unit_id', 'in', $childrenList);
        } else {
            $map = [];
        }
        $unit = Users::field('id,nickname')->where($map)->select()->toArray();
        return $this->response($unit);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/7/4 10:05
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 答题用户
     */
    public function getUserDt()
    {
        //获取本身和下级单位单位的id
        if (!$this->is_super) {
            $childrenList = $this->search->getChildrenIds($this->request->unit_id, true);
            $map[] = array('unit_id', 'in', $childrenList);
        } else {
            $map = [];
        }
        $map[] = array('wx_role_id', '<>', 2);
        $unit = Users::field('id,nickname')->where($map)->select()->toArray();
        return $this->response($unit);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/25
     * @Time: 16:30
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 上传案件统计
     */
    public function isUploadUnit()
    {
        $unit_parent = '';
        if (!empty($this->user)) {
            if ($this->user->unit_id === 0) {
                $unit_parent = '管理员';
            } else {
                $parent = $this->search->getParent($this->user->unit_id);
                $unit_parent = reset($parent)['unit_title'] ?? '未知';
            }
            $childrenList = $this->search->getChildrenIds($this->user->unit_id, true);
            $map[] = array('id', 'in', $childrenList);
        }
        $map[] = array('level', '=', 3);
        $unit_upload = Unit::with(['examAudit'])->field('id,unit_title')->where($map)->select()->filter(function (Unit $unit) {
            if (count($unit['examAudit']) > 0) {
                return true;
            }
        })->toArray();
        $unit_not_upload = Unit::with(['examAudit'])->field('id,unit_title')->where($map)->select()->filter(function (Unit $unit) {
            if (count($unit['examAudit']) === 0) {
                return true;
            }
        })->toArray();
        $data = [
            'count' => count(array_values($unit_upload)) + count(array_values($unit_not_upload)),
            'unit_upload' => count(array_values($unit_upload)),
            'unit_not_upload' => count(array_values($unit_not_upload)),
            'unit_parent' => $unit_parent
        ];
        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/25
     * @Time: 17:03
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 具体细则详情
     */
    public function unitDetail()
    {
        $type_id = $this->request->param('type_id');
        if (!empty($this->user)) {
            $childrenList = $this->search->getChildrenIds($this->user->unit_id, true);
            $map[] = array('id', 'in', $childrenList);
        }
        $map[] = array('level', '=', 3);
        if (intval($type_id) === 1) { //总列表
            $unit = Unit::with(['examAudit'])->field('id,unit_title')->withCount(['examAudit'])->where($map)->order('exam_audit_count desc')->select()->toArray();
        } else if (intval($type_id) === 2) { //已上传网点
            $unit = Unit::with(['examAudit'])->field('id,unit_title')->withCount(['examAudit'])->where($map)->order('exam_audit_count desc')->select()->filter(function (Unit $unit) {
                if (count($unit['examAudit']) > 0) {
                    return true;
                }
            })->toArray();
        } else if (intval($type_id) === 3) { //未上传网点
            $unit = Unit::with(['examAudit'])->field('id,unit_title')->withCount(['examAudit'])->where($map)->order('exam_audit_count desc')->select()->filter(function (Unit $unit) {
                if (count($unit['examAudit']) === 0) {
                    return true;
                }
            })->toArray();
        } else { //未知
            $unit = [];
        }
        return $this->response($unit);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/25
     * @Time: 18:00
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 日常检查
     */
    public function dailyCheck()
    {
        $limit = $this->request->param('limit', 10);
        $type = $this->request->param('type');
        $map = [];
        if ($this->request->has('date_of') && !empty($this->request->param('date_of'))) {
            $map[] = ['date_of', '=', $this->request->param('date_of')];
        }
        if (!empty($this->user)) {
            $childrenList = $this->search->getChildrenIds($this->user->unit_id, true);
            $map[] = array('unit_id', 'in', $childrenList);
        }
        if (intval($type) === 1) {
            $map[] = array('status', '=', 2); //已审核
        } else if (intval($type) === 2) { //待审核
            $map[] = array('status', '=', 1);
        }
        $res = AuditExam::with(['user', 'unit', 'exam', 'admin'])->where($map)->order('id desc')->paginate($limit)->each(function ($item, $key) {
            $unit_parent = $this->search->getParent($item['unit_id']);
            $item['unit_parent'] = reset($unit_parent)['unit_title'] ?? '未知';
            return $item;
        });
        return $this->response($res);
    }

    /**、
     * @User: 刘海龙
     * @Date: 2021/10/26
     * @Time: 10:43
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundExcepti
     * 扣分统计
     */
    public function pointsCount()
    {
        $limit = $this->request->param('limit', 10);
        if (!empty($this->user)) {
            $childrenList = $this->search->getChildrenIds($this->user->unit_id, true);
            $map[] = array('unit_id', 'in', $childrenList);
        }
        $map[] = array('status', '=', 2);
        $map[] = array('deduct_marks', '>', 0);
        $res = AuditExam::with(['user', 'unit', 'exam' => ['examDetail'], 'admin'])->where($map)->withCount(['examFile' => function ($query, &$alias) {
            $query->where(['is_audit' => 1, 'audit_way' => 2]); //扣分数量
            $alias = 'points_count';
            return $query;
        }, 'submit' => 'submit_count', 'unchecked' => function ($q, &$no) {
            $q->where(['is_audit' => 0, 'audit_way' => 0]); //未审核数
            $no = 'unchecked_count';
            return $q;
        }])->order('id desc')->paginate($limit)->each(function ($item, $key) {
            $admin = $item['admin']->toArray();
            if (!empty($admin)) {
                $item['admin_name'] = mb_substr($admin['nickname'], 0, 3, 'utf8');
            }
            $exam = $item['exam']->toArray();
            if (!empty($exam)) {
                if (!empty($exam['examDetail'])) {
                    $item['amount'] = count($exam['examDetail']); //总问卷数
                }
            }
            $unit_parent = $this->search->getParent($item['unit_id']);
            $item['unit_parent'] = reset($unit_parent)['unit_title'] ?? '未知';
            $item['attribute_name'] = Unit::$is_attribute[$item['attribute']] ?? '未知';
            return $item;
        });
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/10/27
     * @Time: 9:42
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 网点排名
     */
    public function unitRank()
    {
        if (!empty($this->user)) {
            $childrenList = $this->search->getChildrenIds($this->user->unit_id, true);
            $map[] = array('unit_id', 'in', $childrenList);
        }
        $limit = $this->request->param('limit', 120);
        if ($this->request->has('date_of') && !empty($this->request->param('date_of'))) {
            $map[] = array('date_of', '=', $this->request->param('date_of'));
        }
        $map[] = array('status', '=', 2);
        $res = AuditExam::field('id,user_id,unit_id,final_score,attribute,date_of,create_time')->with(['user', 'unit', 'admin'])->where($map)->order(['final_score' => 'desc', 'create_time' => 'asc'])->paginate($limit)->each(function ($item, $key) {
            $unit_parent = $this->search->getParent($item['unit_id']);
            $item['attribute_name'] = Unit::$is_attribute[$item['attribute']] ?? '未知';
            $item['unit_parent'] = reset($unit_parent)['unit_title'] ?? '未知';
            return $item;
        });
        if (empty($res)) {
            return $this->response(400, '暂未查询到数据');
        } else {
            return $this->response($res);
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/27
     * @Time: 14:38
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 月报表
     */
    public function monthlyReport()
    {
        if (!empty($this->user)) {
            $childrenList = $this->search->getChildrenIds($this->user->unit_id, true);
            $map[] = array('id', 'in', $childrenList);
        }
        $map[] = array('level', '=', 3);
        $limit = $this->request->param('limit', 10);
        $res = Unit::field('id,unit_title')->withCount(['examAudit' => function ($query) {
            $query->where([]); //'date_of'=>'2021-10-27'
            return $query;
        }, 'fullMarks' => function ($full) {
//            $map[] = array('date_of','=','2021-10-27');
            $map[] = array('deduct_marks', '=', 0);
            $full->where($map);
            return $full;
        }, 'points' => function ($point) {
//            $map[] = array('date_of','=','2021-10-27');
            $map[] = array('deduct_marks', '<>', 0);
            $point->where($map);
            return $point;
        }, 'pending' => function ($pending) {
//            $map[] = array('date_of','=','2021-10-27');
            $map[] = array('status', '=', 1);
            $pending->where($map);
            return $pending;
        }])->where($map)->order('exam_audit_count', 'desc')->paginate($limit)->each(function ($item, $key) {

            $item['title'] = mb_substr($item['unit_title'], 0, 5, 'utf8');
            return $item;
        });
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/28
     * @Time: 10:31
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 答题记录
     */
    public function studyRecord()
    {
        $limit = $this->request->param('limit', 10);
        $map = [];
        if (!empty($this->user)) {
            if ($this->user->unit_id !== 0) {
                $map[] = array('exercise_user_id', '=', $this->user->id);
            }
        }
        $res = TopicExerciseLog::with(['user' => ['unit']])->where($map)->order(['date_of' => 'desc'])->paginate($limit)->each(function ($item, $key) {
            if ($item['type'] !== TopicExerciseLog::TOPIC_FOUR && $item['type'] !== TopicExerciseLog::TOPIC_FIVE) {
                $change_option = TopicExerciseLog::changeOption($item['option'], $item['answer'], $item['user_answer']);
                $item['new_answer'] = $change_option['new_answer'];//新正确答案
                $item['new_my_answer'] = $change_option['new_my_answer']; //新我的答案
                $item['option'] = json_decode($item['option'], true);
                $item['topic'] = TopicExerciseLog::$is_topic[$item['type']];
                return $item;
            }
        });
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/1
     * @Time: 17:26
     * @return \think\response\Json
     * 更改昵称
     */
    public function changeUserInfo()
    {
        $data = $this->request->param();
        $this->user->save(['nickname' => $data['nickname']]);
        if ($this->user['unit'] === null) {
            $this->user['unit'] = [
                'unit_title' => '管理员'
            ];
        }
        return $this->response($this->user->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/1
     * @Time: 17:49
     * @return \think\response\Json
     * 更改密码
     */
    public function changePassword()
    {
        $data = $this->request->param();
        if (!password_verify($data['oldPassword'], $this->user->password)) {
            return $this->response(401, '原始密码错误');
        }
        if ($data['newPassword'] !== $data['confirmPassword']) {
            return $this->response(401, '两次密码输入不一致');
        }
        $this->user->save(['password' => password_hash($data['newPassword'], PASSWORD_DEFAULT)]);
        return $this->response();
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/11/1
     * @Time: 14:56
     * @return \think\response\Json
     * 微信头像上传
     */
    public function WxUploadImg()
    {
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $result = $this->save($file, 'wx_head');
        $head_img = Env::get('HTTP.http', 'HTTP.default_http') . 'storage/' . $result['path'];
        $this->user->save(['head_img' => $head_img]);
        if ($this->user['unit'] === null) {
            $this->user['unit'] = [
                'unit_title' => '管理员'
            ];
        }
        return $this->response($this->user->toArray());
    }


    public function test()
    {
        $res = AuditExam::with(['examFile'])->select()->each(function ($item, $key) {
            AuditExamFile::where(['audit_exam_id' => $item['id']])->update(['attribute' => $item['attribute']]);
        });
        halt(1);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/30
     * @Time: 14:29
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * 是否上传
     */
    public function uploadStatistical()
    {
        $isUpload = $this->request->param('isUpload', 1); //上传
        $limit = $this->request->param('limit', 10);
        $page = $this->request->param('page', 1);

        if (!$this->is_super) {
            $childrenList = $this->search->getChildrenIds($this->request->unit_id, true);
            $map[] = array('id', 'in', $childrenList);
        } else {
            $map = [];
        }
        $where = [];
        if ($this->request->has('date_of') && !empty($this->request->param('date_of'))) {
            $where[] = ['date_of', '=', $this->request->param('date_of')];
        }
        $map[] = array('level', '=', 3);
        $map[] = array('attribute', '<>', 3);
        $res = Unit::field('id,unit_title,level,attribute')->with(['examAudit' => function ($query) use ($where) {
            $query->where($where);
        }])->where($map)->select()->each(function ($item, $key) {
            $unit_parent = $this->search->getParent($item['id']);
            $item['attribute_name'] = Unit::$is_attribute[$item['attribute']] ?? '未知';
            $item['unit_parent'] = reset($unit_parent)['unit_title'] ?? '未知';
            $item['date_of'] = $this->request->param('date_of') ?? '未知';
            return $item;
        })->filter(function (Unit $unit) use ($isUpload) {
            if (intval($isUpload) === 0) {
                if (count($unit->examAudit) == 0) {
                    return true;
                }
            } else {
                if (count($unit->examAudit) > 0) {
                    return true;
                }
            }
        })->toArray();
        $count = count($res);//总条数
        $start = ($page - 1) * $limit;//偏移量，当前页-1乘以每页显示条数
        $list = array_slice($res, $start, $limit);
        $data = [
            'code' => 200,
            'data' => [
                'message' => '执行成功',
                'totalCount' => $count,
                'list' => array_values($list)
            ],

        ];
        return json($data);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/4/20 9:16
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *  //导出问卷
     */
    public function importExcel()
    {
        $data = $this->request->param(); //2029
        $e_id = $this->request->param('id', '2029');
        $audit = AuditExam::with(['user', 'admin', 'unit', 'examFile', 'exam' => ['examStairType' => ['examSecondLevel' => ['examDetail' => ['auditExamFile' => function ($f) use ($e_id) {
            $f->where(['audit_exam_id' => $e_id]);
            return $f;
        }]]], 'examDetail' => ['auditExamFile' => function ($q) use ($e_id) {
            $q->where(['audit_exam_id' => $e_id]);
            return $q;
        }]]])->find($e_id)->toArray();

        $xls = new Spreadsheet();
        $sheet = $xls->getActiveSheet();
        $sheet->setTitle($audit['unit']['unit_title'].'-'.$audit['date_of']);
        $sheet->getColumnDimension('A')->setWidth(30);
        $sheet->getColumnDimension('B')->setWidth(50);
        $sheet->getColumnDimension('C')->setWidth(30);
        $sheet->getColumnDimension('D')->setWidth(50);
        $sheet->setCellValue("A1", '网点名称');
        $sheet->setCellValue("B1", $audit['unit']['unit_title']);
        $sheet->setCellValue("C1", '检查时间');
        $sheet->setCellValue("D1", $audit['date_of']);
        $sheet->setCellValue("A2", '检查人');
        $sheet->setCellValue("B2", $audit['user']['nickname']);
        $sheet->setCellValue("C2", '审核人');
        $sheet->setCellValue("D2", $audit['admin']['nickname']);
        $sheet->setCellValue("A3", '标准分');
        $sheet->setCellValue("B3", $audit['original']);
        $sheet->setCellValue("C3", '实际得分');
        $sheet->setCellValue("D3", $audit['final_score']);
        $sheet->setCellValue("A4", '实际扣分');
        $sheet->setCellValue("B4", $audit['deduct_marks']);
        $sheet->setCellValue("C4", '总指标数');
        $sheet->setCellValue("D4", count($audit['exam']['examDetail']));
        $sheet->setCellValue("A5", '图片数');
        $sheet->setCellValue("B5", count($audit['examFile']));
        $sheet->setCellValue("A6", '项目名称');
        $sheet->setCellValue("B6", '标准分');
        $sheet->setCellValue("C6", '实际得分');
        $sheet->setCellValue("D6", '失分原因');
        $style_header = [
            'alignment' => [
                'horizontal' => 'center',
                'vertical' => 'center',
            ],
            'font' => [
                'size' => 16,
            ],
            'fill' => [
                'fillType' => 'solid',
                'rotation' => 0,
                'startColor' => ['rgb' => '5bbfe1'],
                'endColor' => ['rgb' => '5bbfe1'],
            ],
        ];
        $style_xm = [
            'alignment' => [
                'horizontal' => 'center',
                'vertical' => 'center',
            ],
            'font' => [
                'size' => 14,
            ],
            'fill' => [
                'fillType' => 'solid',
                'rotation' => 0,
                'startColor' => ['rgb' => 'b5b814'],
                'endColor' => ['rgb' => 'b5b814'],
            ],
        ];
        $style_name = [
            'alignment' => [
                'horizontal' => 'center',
                'vertical' => 'center',
            ],
            'font' => [
                'size' => 14,
            ],
            'fill' => [
                'fillType' => 'solid',
                'rotation' => 0,
                'startColor' => ['rgb' => 'fff90c'],
                'endColor' => ['rgb' => 'fff90c'],
            ],
        ];
        $style_fl = [
            'alignment' => [
                'horizontal' => 'center',
                'vertical' => 'center',
            ],
            'font' => [
                'size' => 12,
            ],
            'fill' => [
                'fillType' => 'solid',
                'rotation' => 0,
                'startColor' => ['rgb' => 'afff12'],
                'endColor' => ['rgb' => 'afff12'],
            ],
        ];
        $style_content = [
            'alignment' => [
                'horizontal' => 'left',
                'vertical' => 'center',
                'wrapText' => true,
            ],
            'font' => [
                'size' => 10,
            ],
        ];
        $style_border = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => 'thin',
                    'color' => ['rgb' => '000000'],
                ]
            ]
        ];
        $sheet->getStyle("A1:D5")->applyFromArray($style_header);

        $sheet->getStyle("A6:D6")->applyFromArray($style_name);
        $i = 7;

        foreach ($audit['exam']['examStairType'] as $key => $vf) {
            $sheet->mergeCells("A{$i}:D{$i}"); //合并单元格
            $sheet->setCellValue("A{$i}", $vf['exam_stair_title']);
            $sheet->getStyle("A{$i}:D{$i}")->applyFromArray($style_xm);
            foreach ($vf['examSecondLevel'] as $k => $v) {
                $i1 = ($i + 1);
                $second_standard_score = 0; //二级标准分值
                $second_actual_score = 0; //二级实际得分
                foreach ($v['examDetail'] as $k1 => $v1) {
                    $i2 = ($i + 2);
                    $second_standard_score += $v1['once_deduct_marks']; //二级标准分值 计算方式
                    if(empty($v1['auditExamFile'])){ //判断是否存在图片
                        //当图片为空的时候 得分为0
                        $detail_score = 0; //细则分值
                    }else{
                        //计算得分
                        //把图片的json转为数组 来计算总数
                        $img_arr = json_decode($v1['auditExamFile']['file_path'],true);
                        //拿到指标的最大扣分规则 - most_deduct_marks
                        $most_deduct_marks = $v1['most_deduct_marks'];
                        //拿到指标的扣分规则 -once_deduct_marks
                        $once_deduct_marks = $v1['once_deduct_marks'];
                        //获取图片的总数
                        $img_arr_count = count($img_arr);
                        //判断当前图片是扣分状态还是得分状态 is_audit -- 是否审核  -- 审核方式audit_way 扣分或通过
                        if ($v1['auditExamFile']['is_audit'] === 1){
                            if ($v1['auditExamFile']['audit_way'] === 1){ // 通过
                                $detail_score = $once_deduct_marks; //细则分值
                            }else{ //扣分
                                //图片数 * 最低的扣分细则 $once_deduct_marks
                                $score = $img_arr_count  *  $once_deduct_marks;
                                //由于存在最大扣分规则  一旦扣分超过最大规则  则取最大规则的分值  $most_deduct_marks
                                $detail_score = $score > $most_deduct_marks ? $most_deduct_marks : $score;
                            }
                        }else{
                            //当前属于未审核状态
                            $detail_score = 0;  //细则分值
                        }
                        $second_actual_score += $detail_score;  //二级实际得分 计算方式
                    }
                    $sheet->setCellValue("A{$i1}", $v['exam_second_title']);
                    $sheet->setCellValue("B{$i1}", $second_standard_score);
                    $sheet->setCellValue("C{$i1}", $second_actual_score);
                    $sheet->setCellValue("D{$i1}", ''); //二级的失分原因
                    $sheet->getStyle("A{$i1}:D{$i1}")->applyFromArray($style_fl);
                    $sheet->setCellValue("A{$i2}", $v1['exam_detail_title'] . '-' . $v1['desc']);
                    $sheet->setCellValue("B{$i2}", $v1['once_deduct_marks']);
                    $sheet->setCellValue("C{$i2}", $detail_score);
                    $sheet->setCellValue("D{$i2}", $v1['auditExamFile']['reason']);
                    $sheet->getStyle("A{$i2}:D{$i2}")->applyFromArray($style_content);
                    $i++;
                }
                $i++;
            }
            $i++;
        }
        $j = $i - 1;
        $sheet->getStyle("A1:D{$j}")->applyFromArray($style_border);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        //header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
        header('Content-Disposition: attachment;filename="'.$audit['unit']['unit_title'].'-'.$audit['date_of'].'.xlsx"');//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($xls);
        $writer->save('php://output');
//        //删除清空：
//        $xls->disconnectWorksheets();
//        unset($spreadsheet);
//        exit;

    }



    public function test1(){

//       $res = AuthWxMenu::findWxMenu(16,$this->search);
//       $arr = [];
//       foreach ($res as $key=>$v){
//           $arr[] = $v['id'];
//       }
//       halt($arr);
    }
}
